package com.wiscamp.ninechapters.threeparties.email;

import cube.ddd.aspect.HandleServiceException;
import cube.ddd.domain.BaseDomainService;
import jakarta.validation.constraints.NotBlank;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * Email Service
 */
@Service
public class EmailService extends BaseDomainService {
    private final JavaMailSender mailSender;

    public EmailService(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    /**
     * Sends a simple email
     *
     * @param deliver
     * @param receiver
     * @param carbonCopy
     * @param subject
     * @param content
     * @return
     */
    @HandleServiceException
    public boolean sendSimpleEmail(@NotBlank String deliver, @NotBlank String[] receiver, String[] carbonCopy, @NotBlank String subject, @NotBlank String content) {
        long startTimestamp = System.currentTimeMillis();
        try {
            var message = new SimpleMailMessage();
            message.setFrom(deliver);
            message.setTo(receiver);
            if (Objects.nonNull(carbonCopy))
                message.setCc(carbonCopy);
            message.setSubject(subject);
            message.setText(content);
            mailSender.send(message);
            return true;
        } catch (MailException e) {
            logger.error("Failed to send an email.", e);
            e.printStackTrace();
        }
        return false;
    }
}
